import { put, call, take, fork } from 'redux-saga/effects';
import * as types from '../constants/ActionTypes';
import { loginSuccess, logining, loginFail } from '../actions/login';
import { LOGINURL } from '../constants/Urls';
import { request, requestXML } from '../utils/RequestUtils';
import { json2xml_str } from '../utils/XmlUtils';
import {stringToMD5String } from '../utils/MD5Utils';

export function* requestLogin(uname, pwd) {
  yield put(logining(uname, pwd));
  let p = stringToMD5String(pwd);
  let xml = json2xml_str(JSON.stringify({
    Response: {
      Head: {
        trace_no: '6',
        terminalno: '8',
        tanstype: '10001',
      },
      Body: {
        uname: uname,
        ucode: p,
      }}
  }));
  try{
    const response = yield call(requestXML, 'http://192.168.4.13:8084/icmp-ums/dhc/sys/mobile.do', xml, 15000);
    let Body = response.Response.Body;
    if (Body.respcd == '-1') {
      console.log('请求超时');
      yield put(loginFail('请求超时，请检查网络连接'));
      return;
    }

    if (Body.respcd === '00') {
      yield put(loginSuccess(uname, Body.merid));
    }
    else {
      console.log('登录失败');
      yield put(loginFail(Body.ret_msg));
    }
  }
  catch(e) {
    yield put(loginFail('登录失败'));
  }

}

export function* watchRequestLogin() {
  while(true) {
    const { uname, pwd } = yield take(types.LOGIN);
    yield call(requestLogin, uname, pwd);
  }
} 